package com.zyf.search.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyf.search.dao.ArticleSearchDao;
import com.zyf.search.pojo.Article;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class ArticleSearchServiceImpl {
    @Autowired
    private ArticleSearchDao articleSearchDao;
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    /**
     * 增加文章
     * @param article
     */
    public void add(Article article){
        articleSearchDao.save(article);
    }
    /**
      *根据id查询文章
     */
    public PageInfo selectById(String id,int pageNum,int pageSize){
        Optional<Article> byId = articleSearchDao.findById(id);
        PageHelper.startPage(pageNum, pageSize);
        List<Article> articles = byId.map(Collections::singletonList).orElse(Collections.emptyList());
        PageInfo pageInfo=new PageInfo(articles);
        return pageInfo;
    }
    /**
     * 根据文章内容查询文章
     */
    public PageInfo selectByName(String name,String Content,int pageNum,int pageSize){
        QueryBuilder queryBuilder=new TermQueryBuilder(name, "%"+Content+"%");
        Iterable<Article> search = articleSearchDao.search(queryBuilder);
        PageHelper.startPage(pageNum, pageSize);
        List list=new ArrayList();
        search.forEach(e->list.add(e));
        PageInfo pageInfo=new PageInfo(list);
        return pageInfo;
    }
}
